package com.dmzc.stage2.chapter17;

class ReadWriteLockImpl implements ReadWriteLock {
    private final Object MUTEX = new Object();
    private int writingWriters = 0;
    private int watingWriters = 0;
    private int readingReaders = 0;
    private boolean preferWtiter;

    public ReadWriteLockImpl() {
        this(true);
    }

    public ReadWriteLockImpl(boolean preferWtiter) {
        this.preferWtiter = preferWtiter;
    }

    /**
     * 创建reader锁
     *
     * @return
     */
    @Override
    public Lock readLock() {
        return new ReadLock(this);
    }

    /**
     * 创建write
     *
     * @return
     */
    @Override
    public Lock writeLock() {
        return new WriteLock(this);
    }

    /**
     * 获取当前有多少线程正在执行写操作
     *
     * @return
     */
    @Override
    public int getWritingWriters() {
        return this.writingWriters;
    }

    /**
     * 获取当前有多少线程正在等待获取写入锁
     *
     * @return
     */
    @Override
    public int getWaitingWriters() {
        return this.watingWriters;
    }

    /**
     * 获取当前有多少线程正在等待获取reader锁
     *
     * @return
     */
    @Override
    public int getReadingReaders() {
        return this.readingReaders;
    }

    Object getMUTEX() {
        return this.MUTEX;
    }

    boolean getPreferWriter() {
        return this.preferWtiter;
    }

    void changePrefer(boolean preferWtiter) {
        this.preferWtiter = preferWtiter;
    }

    void incrementWritingWriters() {
        this.writingWriters++;
    }

    void incrementWaitingWriters() {
        this.watingWriters++;
    }

    void incrementReadingReaders() {
        this.readingReaders++;
    }

    void decrementWritingWaiters() {
        this.writingWriters--;
    }

    void decrementWatingWriters() {
        this.watingWriters--;
    }

    void decrementReadingReaders() {
        this.readingReaders--;
    }
}
